﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication2.Controllers
{
    public class PayPalController : Controller
    {
        //
        // GET: /PayPal/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ReturnSuccess()
        {
            var formVals = new Dictionary<string, string> { { "cmd", "_notify-validate" } };

            string response = GetPayPalResponse(formVals, true);
            return View();
        }

        public ActionResult CancelledPayment()
        {
            var formVals = new Dictionary<string, string> { { "cmd", "_notify-validate" } };

            string response = GetPayPalResponse(formVals, true);
            return View("CancelledPayment");
        }

                /// <summary>
                /// Utility method for handling PayPal Responses
                /// </summary>
                string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
                {

                    var paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
                        : "https://www.paypal.com/cgi-bin/webscr";


                    var req = (HttpWebRequest)WebRequest.Create(paypalUrl);

                    // Set values for the request back
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";

                    byte[] param = Request.BinaryRead(Request.ContentLength);
                    string strRequest = Encoding.ASCII.GetString(param);

                    StringBuilder sb = new StringBuilder();
                    sb.Append(strRequest);

                    foreach (string key in formVals.Keys)
                    {
                        sb.AppendFormat("&{0}={1}", key, formVals[key]);
                    }
                    strRequest += sb.ToString();
                    req.ContentLength = strRequest.Length;

                    //for proxy
                    //WebProxy proxy = new WebProxy(new Uri("http://urlort#");
                    //req.Proxy = proxy;
                    //Send the request to PayPal and get the response
                    string response = "";
                    using (var streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
                    {

                        streamOut.Write(strRequest);
                        streamOut.Close();
                        using (var streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
                        {
                            response = streamIn.ReadToEnd();
                        }
                    }

                    return response;
                }
            }
    }



// buyer

//sandbo_1337012948_per@hotmail.it 
//340744797

//using System;
//using System.Collections.Generic;
//using System.Data.SqlClient;
//using System.Diagnostics;
//using System.IO;
//using System.Linq;
//using System.Net;
//using System.Text;
//using System.Web;
//using System.Web.Configuration;
//using System.Web.Mvc;
//using JetBrains.Annotations;
//using NLog;
//using Orchard;
//using Orchard.Logging;
//using Orchard.Themes;

//namespace CheckOutLibrary.Controllers
//{
//    //VPD7CzabnPPhVeDcagcEf1D63DyXwpKbnAOcXzG-MVM4IeuCtsV0WdGyV7y

//    [Themed]
//    public class HomeController : Controller
//    {
//        readonly NLogLogger _logger = new NLogLogger();

//        public ActionResult ReturnSuccess()
//        {
//            _logger.Info("PDT_Entered");

//            var authToken = "VPD7CzabnPPhVeDcagcEf1D63DyXwpKbnAOcXzG-MVM4IeuCtsV0WdGyV7y";

//            //read in txn token from querystring
//            var txToken = Request.QueryString.Get("tx");


//            var query = string.Format("cmd=_notify-synch&tx={0}&at={1}",
//                                  txToken, authToken);

//            // Create the request back
//            string url = "https://www.sandbox.paypal.com/cgi-bin/webscr";

//            //WebConfigurationManager.AppSettings["PayPalSubmitUrl"];
//            var req = (HttpWebRequest)WebRequest.Create(url);

//            // Set values for the request back
//            req.Method = "POST";
//            req.ContentType = "application/x-www-form-urlencoded";
//            req.ContentLength = query.Length;

//            // Write the request back IPN strings
//            var stOut = new StreamWriter(req.GetRequestStream(),
//                                     System.Text.Encoding.ASCII);
//            stOut.Write(query);
//            stOut.Close();

//            // Do the request to PayPal and get the response
//            var stIn = new StreamReader(req.GetResponse().GetResponseStream());
//            var strResponse = stIn.ReadToEnd();
//            stIn.Close();


//            // If response was SUCCESS, parse response string and output details
//            if (strResponse.StartsWith("SUCCESS"))
//            {
//                _logger.Info("PDT_SUCCESS");

//                var pdt = PDTHolder.Parse(strResponse);

//                ViewBag.PayerMail = pdt.PayerEmail;

//                /*
//                 * Cerco di ottenere il seriale se è già stato creato..
//                 * O altrimenti dico che arriva su mail..
//                 */
//                try
//                {
//                    using (var con = new SqlConnection(@"Data Source=tcp:s06.winhost.com;Initial Catalog=DB_33597_orcharddb;User ID=DB_33597_orcharddb_user;Password=webhost001;Integrated Security=False;Enlist=false;"))
//                    {
//                        con.Open();
//                        //
//                        using (var command = new SqlCommand("SELECT * FROM License WHERE TxToken LIKE @Tok", con))
//                        {
//                            //
//                            // Add new SqlParameter to the command.
//                            //
//                            command.Parameters.Add(new SqlParameter("Tok", txToken));
//                            //
//                            // Read in the SELECT results.
//                            //
//                            var reader = command.ExecuteReader();
//                            if (reader != null)
//                            {
//                                while (reader.Read())
//                                {
//                                    var key = reader.GetString(1);

//                                    ViewBag.Key = key;
//                                }
//                            }
//                        }
//                    }
//                }
//                catch (Exception exception)
//                {
//                    _logger.Info(exception.ToString());
//                }
//                //Label1.Text =
//                //    string.Format("Thank you {0} {1} [{2}] for your payment of {3} {4}!",
//                //    pdt.PayerFirstName, pdt.PayerLastName,
//                //    pdt.PayerEmail, pdt.GrossTotal, pdt.Currency);
//            }
//            else
//            {
//                _logger.Info("PDT_FAil");

//                //Label1.Text = "Oooops, something went wrong...";
//            }
//            return View("ReturnSuccess");
//        }

//        public ActionResult CancelledPayment()
//        {
//            _logger.Info("PDT_Entered");

//            return View("CancelledPayment");
//        }


//        public ActionResult Index()
//        {
//            return View("Checkout");
//        }


//        /// <summary>
//        /// Handles the IPN Notification from PayPal
//        /// </summary>
//        /// <returns></returns>
//        public string Ipn()
//        {
//            _logger.Info("Ipn Arrived");

//            var formVals = new Dictionary<string, string> { { "cmd", "_notify-validate" } };

//            string response = GetPayPalResponse(formVals, true);

//            if (response == "VERIFIED")
//            {
//                var transactionId = Request["txn_id"];
//                var sAmountPaid = Request["mc_gross_1"];

//                var payerMail = Request["payer_email"];

//                _logger.Info("IPN - mail " + payerMail);

//                var licenseKey = Guid.NewGuid();
//                _logger.Info("License key : >> " + licenseKey);

//                try
//                {
//                    using (var con = new SqlConnection(@"Data Source=tcp:s06.winhost.com;Initial Catalog=DB_33597_orcharddb;User ID=DB_33597_orcharddb_user;Password=webhost001;Integrated Security=False;Enlist=false;"))
//                    {
//                        con.Open();
//                        using (var command = new SqlCommand(

//                            "INSERT INTO License VALUES(@LicenseKey, @Duration, @Started, @EndTime, @PcLicenseStarted, @Mail, @TxToken)",
//                            con))
//                        {

//                            command.Parameters.Add(new SqlParameter("LicenseKey", licenseKey.ToString()));

//                            command.Parameters.Add(new SqlParameter("Duration", 1.0f));

//                            command.Parameters.Add(new SqlParameter("Started", false));

//                            command.Parameters.Add(new SqlParameter("EndTime", DateTime.Today));

//                            command.Parameters.Add(new SqlParameter("PcLicenseStarted", string.Empty));

//                            command.Parameters.Add(new SqlParameter("Mail", payerMail));

//                            command.Parameters.Add(new SqlParameter("TxToken", transactionId));

//                            command.ExecuteNonQuery();

//                            _logger.Info("Ipn - License key added");


//                            var message = new System.Net.Mail.MailMessage();
//                            message.To.Add(payerMail);
//                            message.Subject = "Licenza Mecprev";
//                            message.From = new System.Net.Mail.MailAddress("info@mecprev.com");
//                            message.Body = "Corpo messaggio : " + licenseKey;

//                            var smtp = new System.Net.Mail.SmtpClient("mail.mecprev.com")
//                                           {
//                                               Credentials = new NetworkCredential("info@mecprev.com", "webhost001")
//                                           };

//                            smtp.Send(message);

//                            _logger.Info("Ipn - Mail sended");

//                            _logger.Info(string.Format("IPN - {0} {1} ha pagato {2} ", Request["first_name"],
//                                                       Request["last_name"], sAmountPaid));
//                        }
//                    }
//                }
//                catch (Exception exception)
//                {
//                    _logger.Info(exception.ToString());
//                }
//            }

//            //   Order order = _orderService.GetOrder(new Guid(orderID));

//            // check the amount paid

//            //    if (AmountPaidIsValid(order, amountPaid))
//            //    {

//            //        Address add = new Address();
//            //        add.FirstName = Request["first_name"];
//            //        add.LastName = Request["last_name"];
//            //        add.Email = Request["payer_email"];
//            //        add.Street1 = Request["address_street"];
//            //        add.City = Request["address_city"];
//            //        add.StateOrProvince = Request["address_state"];
//            //        add.Country = Request["address_country"];
//            //        add.Zip = Request["address_zip"];
//            //        add.UserName = order.UserName;


//            //        order.ShippingAddress = add;
//            //        order.BillingAddress = order.ShippingAddress;
//            //        //process it
//            //        try
//            //        {
//            //            _pipeline.AcceptPalPayment(order, transactionID, amountPaid);
//            //            _logger.Info("IPN Order successfully transacted: " + orderID);
//            //            return RedirectToAction("Receipt", "Order", new { id = order.ID });
//            //        }
//            //        catch (Exception x)
//            //        {
//            //            HandleProcessingError(order, x);
//            //            return View();
//            //        }
//            //    }
//            //    else
//            //    {
//            //        //let fail - this is the IPN so there is no viewer
//            //    }
//            //}



//            // return View();

//            return "IPN";
//        }


//        /// <summary>
//        /// Utility method for handling PayPal Responses
//        /// </summary>
//        string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
//        {

//            var paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
//                : "https://www.paypal.com/cgi-bin/webscr";


//            var req = (HttpWebRequest)WebRequest.Create(paypalUrl);

//            // Set values for the request back
//            req.Method = "POST";
//            req.ContentType = "application/x-www-form-urlencoded";

//            byte[] param = Request.BinaryRead(Request.ContentLength);
//            string strRequest = Encoding.ASCII.GetString(param);

//            StringBuilder sb = new StringBuilder();
//            sb.Append(strRequest);

//            foreach (string key in formVals.Keys)
//            {
//                sb.AppendFormat("&{0}={1}", key, formVals[key]);
//            }
//            strRequest += sb.ToString();
//            req.ContentLength = strRequest.Length;

//            //for proxy
//            //WebProxy proxy = new WebProxy(new Uri("http://urlort#");
//            //req.Proxy = proxy;
//            //Send the request to PayPal and get the response
//            string response = "";
//            using (var streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
//            {

//                streamOut.Write(strRequest);
//                streamOut.Close();
//                using (var streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
//                {
//                    response = streamIn.ReadToEnd();
//                }
//            }

//            return response;
//        }
//    }

//    /* The whole PDT holder class */

//    public class PDTHolder
//    {
//        public double GrossTotal { get; set; }
//        public int InvoiceNumber { get; set; }
//        public string PaymentStatus { get; set; }
//        public string PayerFirstName { get; set; }
//        public double PaymentFee { get; set; }
//        public string BusinessEmail { get; set; }
//        public string PayerEmail { get; set; }
//        public string TxToken { get; set; }
//        public string PayerLastName { get; set; }
//        public string ReceiverEmail { get; set; }
//        public string ItemName { get; set; }
//        public string Currency { get; set; }
//        public string TransactionId { get; set; }
//        public string SubscriberId { get; set; }
//        public string Custom { get; set; }

//        public static PDTHolder Parse(string postData)
//        {
//            String sKey, sValue;
//            PDTHolder ph = new PDTHolder();

//            try
//            {
//                //split response into string array using whitespace delimeter
//                String[] StringArray = postData.Split('\n');

//                // NOTE:
//                /*
//                * loop is set to start at 1 rather than 0 because first
//                string in array will be single word SUCCESS or FAIL
//                Only used to verify post data
//                */

//                // use split to split array we already have using "=" as delimiter
//                int i;
//                for (i = 1; i < StringArray.Length - 1; i++)
//                {
//                    String[] StringArray1 = StringArray[i].Split('=');

//                    sKey = StringArray1[0];
//                    sValue = HttpUtility.UrlDecode(StringArray1[1]);

//                    // set string vars to hold variable names using a switch
//                    switch (sKey)
//                    {
//                        case "mc_gross":
//                            ph.GrossTotal = Convert.ToDouble(sValue);
//                            break;

//                        case "invoice":
//                            ph.InvoiceNumber = Convert.ToInt32(sValue);
//                            break;

//                        case "payment_status":
//                            ph.PaymentStatus = Convert.ToString(sValue);
//                            break;

//                        case "first_name":
//                            ph.PayerFirstName = Convert.ToString(sValue);
//                            break;

//                        case "mc_fee":
//                            ph.PaymentFee = Convert.ToDouble(sValue);
//                            break;

//                        case "business":
//                            ph.BusinessEmail = Convert.ToString(sValue);
//                            break;

//                        case "payer_email":
//                            ph.PayerEmail = Convert.ToString(sValue);
//                            break;

//                        case "Tx Token":
//                            ph.TxToken = Convert.ToString(sValue);
//                            break;

//                        case "last_name":
//                            ph.PayerLastName = Convert.ToString(sValue);
//                            break;

//                        case "receiver_email":
//                            ph.ReceiverEmail = Convert.ToString(sValue);
//                            break;

//                        case "item_name":
//                            ph.ItemName = Convert.ToString(sValue);
//                            break;

//                        case "mc_currency":
//                            ph.Currency = Convert.ToString(sValue);
//                            break;

//                        case "txn_id":
//                            ph.TransactionId = Convert.ToString(sValue);
//                            break;

//                        case "custom":
//                            ph.Custom = Convert.ToString(sValue);
//                            break;

//                        case "subscr_id":
//                            ph.SubscriberId = Convert.ToString(sValue);
//                            break;
//                    }
//                }

//                return ph;
//            }
//            catch (Exception ex)
//            {
//                throw ex;
//            }
//        }
//    }
//    public class NLogLogger
//    {
//        private readonly Logger _logger;

//        public NLogLogger()
//        {
//            _logger = LogManager.GetCurrentClassLogger();
//        }

//        public void Info(string message)
//        {
//            _logger.Info(message);
//        }

//        public void Warn(string message)
//        {
//            _logger.Warn(message);
//        }

//        public void Debug(string message)
//        {
//            _logger.Debug(message);
//        }

//        public void Error(string message)
//        {
//            _logger.Error(message);
//        }
//        public void Error(Exception x)
//        {
//            Error(LogUtility.BuildExceptionMessage(x));
//        }
//        public void Fatal(string message)
//        {
//            _logger.Fatal(message);
//        }
//        public void Fatal(Exception x)
//        {
//            Fatal(LogUtility.BuildExceptionMessage(x));
//        }
//    }
//    public class EventLogLogger
//    {
//        #region ILogger Members

//        public void Info(string message)
//        {
//            WriteToEventLog(message, EventLogEntryType.Information);
//        }

//        public void Warn(string message)
//        {
//            WriteToEventLog(message, EventLogEntryType.Warning);
//        }

//        public void Debug(string message)
//        {
//            //no need to send this to the EventLog - output it 
//            //to the DEBUG window
//            System.Diagnostics.Debug.WriteLine(message);
//        }

//        public void Error(string message)
//        {
//            WriteToEventLog(message, EventLogEntryType.Error);
//        }

//        public void Error(Exception x)
//        {
//            Error(LogUtility.BuildExceptionMessage(x));
//        }

//        public void Fatal(string message)
//        {
//            WriteToEventLog(message, EventLogEntryType.Error);
//        }
//        public void Fatal(Exception x)
//        {
//            WriteToEventLog(LogUtility.BuildExceptionMessage(x), EventLogEntryType.Error);
//        }


//        void WriteToEventLog(string message, EventLogEntryType logType)
//        {

//            EventLog eventLog = new EventLog();

//            //use the app log - you can customize this as you need
//            string storeName = System.Configuration
//                .ConfigurationManager.AppSettings["StoreName"].ToString();
//            eventLog.Source = storeName;

//            eventLog.WriteEntry(message, logType);
//        }
//        #endregion


//    }

//    public class LogUtility
//    {

//        public static string BuildExceptionMessage(Exception x)
//        {
//            Exception logException = x;
//            if (x.InnerException != null)
//                logException = x.InnerException;

//            string strErrorMsg = Environment.NewLine + "Error in Path :" + System.Web.HttpContext.Current.Request.Path;

//            // Get the QueryString along with the Virtual Path
//            strErrorMsg += Environment.NewLine + "Raw Url :" + System.Web.HttpContext.Current.Request.RawUrl;


//            // Get the error message
//            strErrorMsg += Environment.NewLine + "Message :" + logException.Message;

//            // Source of the message
//            strErrorMsg += Environment.NewLine + "Source :" + logException.Source;

//            // Stack Trace of the error

//            strErrorMsg += Environment.NewLine + "Stack Trace :" + logException.StackTrace;

//            // Method where the error occurred
//            strErrorMsg += Environment.NewLine + "TargetSite :" + logException.TargetSite;
//            return strErrorMsg;
//        }
//    }

//}
////public class HomeController : Controller
////{
////    readonly NLogLogger _logger = new NLogLogger();

////    public ActionResult Index()
////    {
////        _logger.Info("kkk");
////        return View("Checkout");
////    }

////    public ActionResult Cancel()
////    {
////        return View("CancelPayment");


////    }


////    /// <summary>
////    /// Handles the IPN Notification from PayPal
////    /// </summary>
////    /// <returns></returns>
////    public string IPN()
////    {
////        return "Pollo";
////        //_logger.Info("IPN Invoked");

////        //var formVals = new Dictionary<string, string>();
////        //formVals.Add("cmd", "_notify-validate");

////        //string response = GetPayPalResponse(formVals, true);

////        //if (response == "VERIFIED")
////        //{

////        //    string transactionID = Request["txn_id"];
////        //    string sAmountPaid = Request["mc_gross"];
////        //    string orderID = Request["custom"];

////        //  _logger.Info("IPN Verified for order " + orderID);

////        //validate the order
////        //Decimal amountPaid = 0;
////        //Decimal.TryParse(sAmountPaid, out amountPaid);

////        //  Order order = _orderService.GetOrder(new Guid(orderID));

////        //check the amount paid

////        //    if (AmountPaidIsValid(order, amountPaid))
////        //    {

////        //        Address add = new Address();
////        //        add.FirstName = Request["first_name"];
////        //        add.LastName = Request["last_name"];
////        //        add.Email = Request["payer_email"];
////        //        add.Street1 = Request["address_street"];
////        //        add.City = Request["address_city"];
////        //        add.StateOrProvince = Request["address_state"];
////        //        add.Country = Request["address_country"];
////        //        add.Zip = Request["address_zip"];
////        //        add.UserName = order.UserName;


////        //        order.ShippingAddress = add;
////        //        order.BillingAddress = order.ShippingAddress;
////        //        //process it
////        //        try
////        //        {
////        //            _pipeline.AcceptPalPayment(order, transactionID, amountPaid);
////        //            _logger.Info("IPN Order successfully transacted: " + orderID);
////        //            return RedirectToAction("Receipt", "Order", new { id = order.ID });
////        //        }
////        //        catch (Exception x)
////        //        {
////        //            HandleProcessingError(order, x);
////        //            return View();
////        //        }
////        //    }
////        //    else
////        //    {
////        //        //let fail - this is the IPN so there is no viewer
////        //    }
////        //}



////        //  return View();
////    }

////    public class LogUtility
////    {

////        public static string BuildExceptionMessage(Exception x)
////        {
////            Exception logException = x;
////            if (x.InnerException != null)
////                logException = x.InnerException;

////            string strErrorMsg = Environment.NewLine + "Error in Path :" + System.Web.HttpContext.Current.Request.Path;

////            // Get the QueryString along with the Virtual Path
////            strErrorMsg += Environment.NewLine + "Raw Url :" + System.Web.HttpContext.Current.Request.RawUrl;


////            // Get the error message
////            strErrorMsg += Environment.NewLine + "Message :" + logException.Message;

////            // Source of the message
////            strErrorMsg += Environment.NewLine + "Source :" + logException.Source;

////            // Stack Trace of the error

////            strErrorMsg += Environment.NewLine + "Stack Trace :" + logException.StackTrace;

////            // Method where the error occurred
////            strErrorMsg += Environment.NewLine + "TargetSite :" + logException.TargetSite;
////            return strErrorMsg;
////        }
////    }

////    public class NLogLogger
////    {
////        private readonly Logger _logger;

////        public NLogLogger()
////        {
////            _logger = LogManager.GetCurrentClassLogger();
////        }

////        public void Info(string message)
////        {
////            _logger.Info(message);
////        }

////        public void Warn(string message)
////        {
////            _logger.Warn(message);
////        }

////        public void Debug(string message)
////        {
////            _logger.Debug(message);
////        }

////        public void Error(string message)
////        {
////            _logger.Error(message);
////        }
////        public void Error(Exception x)
////        {
////            Error(LogUtility.BuildExceptionMessage(x));
////        }
////        public void Fatal(string message)
////        {
////            _logger.Fatal(message);
////        }
////        public void Fatal(Exception x)
////        {
////            Fatal(LogUtility.BuildExceptionMessage(x));
////        }
////    }
////    public class EventLogLogger
////    {
////        #region ILogger Members

////        public void Info(string message)
////        {
////            WriteToEventLog(message, EventLogEntryType.Information);
////        }

////        public void Warn(string message)
////        {
////            WriteToEventLog(message, EventLogEntryType.Warning);
////        }

////        public void Debug(string message)
////        {
////            //no need to send this to the EventLog - output it 
////            //to the DEBUG window
////            System.Diagnostics.Debug.WriteLine(message);
////        }

////        public void Error(string message)
////        {
////            WriteToEventLog(message, EventLogEntryType.Error);
////        }

////        public void Error(Exception x)
////        {
////            Error(LogUtility.BuildExceptionMessage(x));
////        }

////        public void Fatal(string message)
////        {
////            WriteToEventLog(message, EventLogEntryType.Error);
////        }
////        public void Fatal(Exception x)
////        {
////            WriteToEventLog(LogUtility.BuildExceptionMessage(x), EventLogEntryType.Error);
////        }


////        void WriteToEventLog(string message, EventLogEntryType logType)
////        {

////            EventLog eventLog = new EventLog();

////            //use the app log - you can customize this as you need
////            string storeName = System.Configuration
////                .ConfigurationManager.AppSettings["StoreName"].ToString();
////            eventLog.Source = storeName;

////            eventLog.WriteEntry(message, logType);
////        }
////        #endregion
////    }
////}
//*/